<template>
  <!-- 我已审核页面 -->
  <div class="box">
    <div class="row_top">
      <van-sticky>
        <van-row>
          <van-col
            span="12"
            @click="show = true"
            :style="{fontSize:'16px'}"
          >{{title_top}}
            <van-icon name="arrow-down" />
          </van-col>
          <van-col
            span="12"
            @click="time_one = true"
            :style="{fontSize:'16px'}"
          >{{data_time}}
            <van-icon name="arrow-down" />
          </van-col>
          <!-- 时间插件 -->
          <van-popup
            v-model="time_one"
            :safe-area-inset-bottom="true"
            :style="{width:'86%',fontSize:'14px',borderRadius:'10px'}"
            :overlay-style="{background:'rgba(0, 0, 0, 0.34)'}"
          >
            <van-datetime-picker
              v-model="currentDate"
              :min-date="minDate"
              :max-date="maxDate"
              type="date"
              @confirm="getTime_one"
              @cancel="show_time_end"
            />

          </van-popup>
          <!-- 类型筛选 -->
          <van-popup
            v-model="show"
            :safe-area-inset-bottom="true"
            :style="{ width:'54%',fontSize:'14px',borderRadius:'10px'}"
            :overlay-style="{background:'rgba(0, 0, 0, 0.34)'}"
          >
            <van-radio-group v-model="radio">
              <van-cell-group :style="{textAlign:'left'}">
                <van-cell
                  :title="it.name"
                  clickable
                  @click="showStatus(it.name,it.index)"
                  v-for="(it,k) in Choice"
                  :key="k"
                >
                  <van-radio
                    slot="icon"
                    :name="it.index"
                    :style="{marginRight:'4vw'}"
                  />
                </van-cell>
              </van-cell-group>
            </van-radio-group>
          </van-popup>
        </van-row>
      </van-sticky>
    </div>
    <div style="background-color: #f8f4f4;">
      <van-row class="vanRow">
        <span class="left">开启批量审批</span>
        <van-switch
          :value="checked"
          @input="onInput"
          size="24px"
        />
      </van-row>
      <van-list
        v-model="loading"
        :finished="finished"
        :offset="10"
        :immediate-check="false"
        finished-text="我是有底线的"
        @load="onLoad"
      >
        <div
          v-for="(item,i) in arr"
          :key="i"
        >
          <div
            class="skeleton clearfix"
            style="margin:10px;position:relative"
          >
            <!-- 开启批量审批  :key="q+'1'" v-for="(tr,q) in item.approvalevent.approvalderive" -->

            <div v-if='checked==true'>
              <div
                v-show="show_red"
                v-if="item.status==0||item.status==1"
                class="right"
                style="width:6px;height:6px;background:red;border-radius:50%;margin:5px 10px"
              ></div>
              <van-checkbox-group
                v-model="result"
                v-show="button"
                :max="5"
                @change="results(result)"
              >
                <van-checkbox
                  :name="item"
                  :style="{position:'absolute',right:'8px',zIndex:'1'}"
                ></van-checkbox>
              </van-checkbox-group>
              <div class="skeleton_content">
                <div
                  class="skeleton_title left"
                  v-if="item.create_name.length<3"
                >
                  {{((item.create_name.split("").reverse().join("")).substring(0,1)).split("").reverse().join("")}}
                </div>
                <div
                  class="skeleton_title left"
                  v-if="item.create_name.length>=3"
                >
                  {{((item.create_name.split("").reverse().join("")).substring(0,2)).split("").reverse().join("")}}
                </div>
                <ul>
                  <li>{{item.create_name}}</li>
                  <li style="margin-bottom:10px">{{item.create_date}}</li>
                </ul>

              </div>
              <ul style="padding:10px">
                <li style="margin-bottom:45px;overflow-wrap:break-word;width:75vw">{{item.approvalevent.event_name}}</li>
                <!-- <li style=" font-size: 13px;margin-bottom:10px">1111</li> -->
                <li style=" font-size: 13px;color:silver;">{{item.approvalevent.date}}</li>
              </ul>
              <div
                class="right"
                style="position:absolute;bottom:10px;right:15px"
              >
                <!-- v-for="(item1 ,i) in item.approvalevent.approvalderive" -->
                <!-- :key="i" -->
                <p>
                  <span>{{D_name}}:<span v-if='item.approvalevent.approvalderive[0].code_b.toString().indexOf("-") != -1'>{{item.approvalevent.approvalderive[0].code_b}}</span>
                    <span v-else>+{{item.approvalevent.approvalderive[0].code_b}}</span>
                  </span>
                  <span v-if="ISC == 1" :class="item.approvalevent.approvalderive[0].code_c==0?'active':'active1'">{{C_name}}: <span v-if='item.approvalevent.approvalderive[0].code_c.toString().indexOf("-") != -1'>{{item.approvalevent.approvalderive[0].code_c}}</span><span v-else>+{{item.approvalevent.approvalderive[0].code_c}}</span></span>
                </p>
                <p
                  class="right"
                  style="font-size:14px;color:silver;"
                  v-for="(item2,i) in status"
                  :key="i"
                > <span v-if="item.status==item2.index">{{item2.name}}</span></p>
              </div>
            </div>
            <!-- 关闭批量审批 -->
            <div
              v-else
              @click="showInitial(item.status,item.approvalevent)"
            >
              <div
                v-show="show_red"
                v-if="item.status==0||item.status==1"
                class="right"
                style="width:6px;height:6px;background:red;border-radius:50%;margin:5px 10px"
              ></div>
              <!-- <van-checkbox-group
                v-model="result"
                v-show="button"
              >
                <van-checkbox
                  :name="i"
                  @click="show_checkbox"
                  :style="{position:'absolute',right:'8px',zIndex:'33'}"
                ></van-checkbox>
              </van-checkbox-group> -->
              <div class="skeleton_content">
                <div
                  class="skeleton_title left"
                  v-if="item.create_name.length<3"
                >
                  {{((item.create_name.split("").reverse().join("")).substring(0,1)).split("").reverse().join("")}}
                </div>
                <div
                  class="skeleton_title left"
                  v-if="item.create_name.length>=3"
                >
                  {{((item.create_name.split("").reverse().join("")).substring(0,2)).split("").reverse().join("")}}
                </div>
                <ul>
                  <li>{{item.create_name}}</li>
                  <li style="margin-bottom:10px">{{item.create_date}}</li>
                </ul>

              </div>
              <ul style="padding:10px">
                <li style="margin-bottom:45px;overflow-wrap:break-word;width:75vw">{{item.approvalevent.event_name}}</li>
                <!-- <li style=" font-size: 13px;margin-bottom:10px">1111</li> -->
                <li style=" font-size: 13px;color:silver;">{{item.approvalevent.date}}</li>
              </ul>
              <div
                class="right"
                style="position:absolute;bottom:10px;right:15px"
              >
                <!-- v-for="(item1 ,i) in item.approvalevent.approvalderive" -->
                <!-- :key="i" -->
                <p>
                  <span>{{D_name}}:
                    <span v-if='item.approvalevent.approvalderive[0].code_b.toString().indexOf("-") > -1'>{{item.approvalevent.approvalderive[0].code_b}}</span>
                    <span v-else>+{{item.approvalevent.approvalderive[0].code_b}}</span>
                  </span>
                  <span v-if="ISC == 1" :class="item.approvalevent.approvalderive[0].code_c==0?'active':'active1'">{{C_name}}: <span v-if='item.approvalevent.approvalderive[0].code_c.toString().indexOf("-") != -1'>{{item.approvalevent.approvalderive[0].code_c}}</span><span v-else>+{{item.approvalevent.approvalderive[0].code_c}}</span></span>
                </p>
                <p
                  class="right"
                  style="font-size:14px;color:silver;"
                  v-for="(item2,i) in status"
                  :key="i"
                > <span v-if="item.status==item2.index">{{item2.name}}</span></p>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <div>
      <van-dialog
        v-model="show_dialog"
        title="审批意见"
        show-cancel-button
        @confirm='showConfirm'
      >
        <van-field
          v-model="field_value"
          :style="{fontSize:'16px',textAlign:'center'}"
        />
      </van-dialog>
    </div>
    <div
      v-show="button"
      class="btn_show"
    >
      <van-button
        plain
        type="info"
        @click="show_noAgree"
      >驳回</van-button>
      <van-button
        @click="show_agree"
        type="info"
      >同意</van-button>
    </div>
    <div
      style="font-size:14px;padding-top:10px;"
      v-show="showText"
      v-cloak
    >暂无数据！</div>
  </div>
</template>

<script type="text/javascript">
import {
  Row,
  Col,
  Icon,
  Popup,
  RadioGroup,
  Radio,
  Cell,
  CellGroup,
  Switch,
  Button,
  Checkbox,
  CheckboxGroup,
  Dialog,
  Field,
  Toast
} from "vant";
import { DatetimePicker } from "vant";
export default {
  data() {
    return {
      radio: 0,
      show_dialog: false,
      showText: false,
      show_red: true,
      button: false,
      show: false,
      time_one: false,
      time_two: false,
      date: 0,
      checked: false,
      loading: false, // 上拉加载
      finished: false, // 上拉加载完毕
      offset: 100, // 滚动条与底部距离小于 offset 时触发load事件
      pageSize: 10, // 每页条数
      pageIndex: 1,
      jp: 0,
      result: [],
      arr: [],
      status: [
        {
          index: 0,
          name: "初审中"
        },
        {
          index: 1,
          name: "终审中"
        },
        {
          index: 2,
          name: "通过"
        },
        {
          index: 3,
          name: "驳回"
        },
        {
          index: 4,
          name: "撤回"
        }
      ],
      Choice: [
        {
          index: 0,
          name: "待我审核"
        },
        {
          index: 1,
          name: "我已审核"
        }
      ],
      title_top: "待我审核",
      minDate: new Date(2018, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      data_time: "时间",
      num: 0,
      people_userId: 0,
      C_name: "C分",
      D_name: "D分",
      field_value: "同意",
      isField: 0,
      all_btn: 0,
      ISC:''
    };
  },
  created() {
    this.radio = 0;
    this.getUserId();
    dd.biz.navigation.setTitle({
      title: "我的审核" //控制标题文本，空字符串表示显示默认文本
    });
  },
  beforeUpdate(){
    this.C_name = localStorage.getItem("c_name");
    this.D_name = localStorage.getItem("d_name");
  },
  methods: {
    /**
     * rfj
     * 审核
     *
     */
     //C分开关
    async getIsC(){
      let corpId = localStorage.getItem("custid");
      const res = await this.$http.get(
        `yuepoints/getIsC?corpId=${corpId}`
      );
      // localStorage.setItem("ISC", res.data.data.is_c_code);
      this.ISC = res.data.data.is_c_code
    },
     // 钉钉鉴权
    async show_js_api() {
      let corpId = localStorage.getItem("custid");
      // let corpId = this.$utils.getUrlKey("custid");
      let url = location.href.split("#")[0];
      const res = await this.$http.get(
        `dingapi/getJsapiConfig?corpId=${corpId}&url=${url}`
      );
      let config = res.data.data;
      localStorage.setItem("appId", config.agentId);
      dd.config({
        agentId: config.agentId,
        corpId: config.corpId,
        timeStamp: config.timeStamp,
        nonceStr: config.nonceStr,
        signature: config.signature,
        jsApiList: [
          "runtime.info",
          "biz.ding.post",
          "biz.ding.create",
          "biz.chat.pickConversation",
          "device.notification.prompt",
          "device.notification.confirm",
          "device.notification.alert",
          "biz.navigation.setRight",
          "biz.chat.open",
          "biz.util.open",
          'biz.util.openLink',
          "biz.user.get",
          "biz.contact.choose",
          "biz.telephone.call",
          "biz.util.uploadImage",
          // "device.accelerometer.watchShake",
          // "biz.map.locate",
          // "device.geolocation.get",
          "biz.customContact.choose",
          "biz.contact.complexPicker",
          "biz.contact.departmentsPicker",
        ]
      });
    },
    // 自定义名称存储
    async getCustomName() {
      let corpId = localStorage.getItem("custid");
      const res = await this.$http.get(
        `yuepoints/getCustomName?corpId=${corpId}`
      );
      if (res.data.errcode == "0000") {
        if (res.data.data.c_name == "") {
          localStorage.setItem("c_name", "C分");
        } else {
          localStorage.setItem("c_name", res.data.data.c_name);
        }
        if (res.data.data.d_name == "") {
          localStorage.setItem("d_name", "D分");
        } else {
          localStorage.setItem("d_name", res.data.data.d_name);
        }
      } else {
        localStorage.setItem("c_name", "C分");
        localStorage.setItem("d_name", "D分");
      }
    },
    //鉴权
    async getUserId() {
      let Corp_Id = localStorage.getItem("custid");
      let User_Id = localStorage.getItem("userId");
      let corpId = this.$utils.getUrlKey("custid");
      if(corpId == null || corpId == "undefined"){
        corpId = Corp_Id
      }else{
        localStorage.setItem("custid", corpId);
      }
      var _this = this;
      let code = '';
      if (User_Id && User_Id != "undefined" && User_Id != null) {
        if (Corp_Id != corpId) {
         await dd.runtime.permission.requestAuthCode({
                corpId: corpId,
                onSuccess: function(result) {
                  code = result.code
                },
                onFail: function(err) {
                }
              });
          _this.$http
              .get(
                `dingapi/signIn?corpId=${corpId}&code=${code}`
              )
              .then(res => {
                localStorage.setItem("userId", res.data.data.dd_id);
                localStorage.setItem("custid", corpId);
                _this.getCustomName();
                _this.getExamine(0);
                _this.show_js_api();
                _this.getIsC();
              })
              
        }else{
            _this.getExamine(0);
            _this.show_js_api();
            _this.getIsC();
        }
      } else {
       await dd.runtime.permission.requestAuthCode({
                corpId: corpId,
                onSuccess: function(result) {
                  code = result.code
                },
                onFail: function(err) {
                }
              });
          _this.$http
            .get(
              `dingapi/signIn?corpId=${corpId}&code=${code}`
            )
            .then(res => {
              localStorage.setItem("userId", res.data.data.dd_id);
              localStorage.setItem("custid", corpId);
              _this.getCustomName();
              _this.getExamine(0);
              _this.show_js_api();
              _this.getIsC();
            })
      }
    },
    results(result){
      if(result.length == 5){
        Toast("最多只能选择五条数据");
      }
    },
    // 审核同意按钮
    showConfirm() {
      let userId = localStorage.getItem("userId");
      let corpId = localStorage.getItem("custid");
      let res_str = "";
      // if (this.result.length > 5) {
      //   Toast("最多只能选择五条数据");
      //   return;
      // }
      
      if (this.result.length <= 1) {
        if (this.isField == 0) {
          let is_status;
          if (this.result[0].status == 0) {
            is_status = 1;
          } else {
            is_status = 2;
          }
          this.showPublic(
            corpId,
            userId,
            is_status,
            this.result[0].id,
            this.field_value,
            this.result[0].status
          );
        } else if (this.isField == 1) {
          this.showPublic(
            corpId,
            userId,
            3,
            this.result[0].id,
            this.field_value,
            this.result[0].status
          );
        }
      } else {
        for (let i = 0; i < this.result.length; i++) {
          res_str += `${this.result[i].id},`;
        }
        if (this.isField == 0) {
          this.show_All(corpId, userId, 1, res_str, this.field_value);
        } else if (this.isField == 1) {
          this.show_All(corpId, userId, 2, res_str, this.field_value);
        }
      }
    },
    async show_All(corpId, userId, status, idList, desc) {
     Toast.loading({
          message: "数据提交中",
          forbidClick: true,
          loadingType: "spinner"
        });
     const res = await this.$http.get(
        `yuepoints/batchAudit?corpId=${corpId}&userId=${userId}&status=${status}&idList=${idList}&desc=${desc}`
      );
      if (res.data.errcode == "0000") {
        this.result = [];
        this.getExamine(0);
        if(status == 1){
          Toast.success('审核成功');
        }else if(status == 2){
          Toast.success('驳回成功');
        }
        this.button = false;
        this.show_red = true;
        this.checked = false;
      }else{
       if(status == 1){
          Toast.success('审核失败');
        }else if(status == 2){
          Toast.success('驳回失败');
        } 
      }
    },
    // 审核取消按钮
    async showPublic(corpId, userId, status, id, desc, type) {
       Toast.loading({
          message: "数据提交中",
          forbidClick: true,
          loadingType: "spinner"
        });
      const res = await this.$http.get(
        `yuepoints/toExamine?corpId=${corpId}&userId=${userId}&status=${status}&id=${id}&desc=${desc}&type=${type}`
      );
      if (res.data.errcode == "0000") {
        this.getExamine(0);
        Toast.success('驳回成功');
        this.button = false;
        this.show_red = true;
        this.checked = false;
      }else{
        Toast.fail('驳回失败');
      }
    },
    // 驳回
    show_noAgree() {
      if (this.result.length == 0) {
        this.$toast("请选择审核事件");
        return;
      }
      this.isField = 1;
      this.field_value = "驳回";
      this.show_dialog = true;
    },
    // 同意事件
    show_agree() {
      if (this.result.length == 0) {
        this.$toast("请选择审核事件");
        return;
      }
      this.isField = 0;
      this.field_value = "同意";
      this.show_dialog = true;
    },
    // 时间取消
    show_time_end() {
      this.data_time = "时间";
      this.currentDate = new Date();
      this.getExamine(0);
      this.time_one = false;
    },
    // 时间筛选
    getTime_one(time) {
      const d = new Date(time);
      let yy = d.getFullYear();
      let mm = this.p(d.getMonth() + 1);
      let dd = this.p(d.getDate());
      const resDate = yy + "-" + mm + "-" + dd;
      this.data_time = resDate;
      this.time_one = false;
      this.getExamine(0, resDate);
      // }
    },
    p(s) {
      return s < 10 ? "0" + s : s;
    },
    onLoad() {
      const p = this.jp;
      this.pageIndex++;
      this.getExamine(p, this.data_time);
    },
    // 我已审核
    async getExamine(cursor, year) {
      this.loading=true;
      let corpId = localStorage.getItem("custid");
      let userId = localStorage.getItem("userId");
      if (userId == null || userId == "undefined") {
        // Toast("请在钉钉工作台悦积分入口进入查看");
        this.$router.replace("/error");
        return false;
      }
      if (year == undefined || year == "时间") {
        year = "";
      }
      await this.$http
        .get(
          `yuepoints/Myaudit?corpId=${corpId}&userId=${userId}&status=1&cursor=${cursor}&date=${year}`
        )
        .then(res => {
          const {
            data: { event },
            data,
            cursor,
            errcode
          } = res.data;
          if (errcode == "0000") {
            this.loading=false
            this.$forceUpdate();
            if (event.length == 0 || event == null || data == "") {
              this.finished = true;
              return;
            }
            if (event.length < this.pageSize) {
              this.finished = true;
            }
            if (this.pageIndex == 1) {
              this.arr = event;
            } else {
              this.arr = this.arr.concat(event);
            }
            if (cursor > 0) {
              this.jp = cursor;
            }
          } else {
              if(this.arr.length<5){
              this.arr=[]
              }
            this.finished = true;
          }
        })
        .catch(error => {})
        .finally(() => {
          this.loading = false;
        });
    },
    // 状态选择
    showStatus(name, i) {
      this.num = i;
      this.title_top = "待我审核";
      if (Number(i) == 1) {
        // this.$router.replace("/myComplete");
         this.$router.push({path:"/myComplete"});
      }
      this.show = false;
    },
    //批量选择
    onInput(checked) {
      this.checked = checked;
      if (checked == true) {
        this.button = true;
        this.show_red = false;
      } else {
        this.button = false;
        this.show_red = true;
      }
    },
    // 初审
    showInitial(status, li) {
      let id;
      for (let i = 0; i < li.approvalderive.length; i++) {
        id = li.approvalderive[i].a_id;
        if (status != 0) {
          this.$router.push({
            //核心语句
            path: "/end", //跳转的路径
            query: {
              //路由传参时push和query搭配使用 ，作用时传递参数
              id: id
            }
          });
        } else {
          this.$router.push({
            path: "/initial", //跳转的路径
            query: {
              //路由传参时push和query搭配使用 ，作用时传递参数
              status: 1,
              id: id
            }
          });
        }
      }
    },
    // 终审
    showEnd(status, li) {
      let id;
      for (let i = 0; i < li.approvalderive.length; i++) {
        id = li.approvalderive[i].a_id;
        if (status == 1) {
          this.$router.push({
            //核心语句
            path: "/end", //跳转的路径
            query: {
              //路由传参时push和query搭配使用 ，作用时传递参数
              id: id,
              status: 2
            }
          });
        } else {
          this.$router.push({
            //核心语句
            path: "/initial", //跳转的路径
            query: {
              //路由传参时push和query搭配使用 ，作用时传递参数
              status: 2,
              id: id
            }
          });
        }
      }
    }
  },
  components: {
    [Row.name]: Row,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [DatetimePicker.name]: DatetimePicker,
    [Switch.name]: Switch,
    [Button.name]: Button,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Dialog.Component.name]: Dialog.Component,
    [Field.name]: Field
  }
};
</script>

<style lang="less" scoped>
.box {
  font-size: 15px;
  background-color: #f8f4f4;
  padding-bottom: 55px;
  .btn_show {
    position: fixed;
    bottom: 55px;
    right: 10px;
    z-index: 2;
  }
  @media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
    .btn_show {
      position: fixed;
      bottom: 100px;
      right: 10px;
      z-index: 2;
    }
  }
  @media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) {
    .btn_show {
      position: fixed;
      bottom: 100px;
      right: 10px;
      z-index: 2;
    }
  }
  @media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) {
    .btn_show {
      position: fixed;
      bottom: 100px;
      right: 10px;
      z-index: 2;
    }
  }
  //   height: 92vh;
  /deep/.van-field__control {
    text-align: center;
  }
  /deep/ .van-sticky {
    background: #fff;
  }
  /deep/ .van-checkbox__icon {
    height: 30px;
  }
  .vanRow {
    border-top: 1px solid rgba(192, 192, 192, 0.288);
    padding: 5px 20px;
    line-height: 5vh;
    background: #fff;
  }
  /deep/ .van-switch {
    margin-top: 5px;
    float: right;
  }
  p {
    margin: 0px;
  }
  .row_top {
    background-color: #fff;
    height: 45x;
    line-height: 45px;
  }
  .skeleton {
    background: #fff;
    padding: 10px 0px 0px 10px;
    text-align: left;
    .skeleton_title {
      color: #fff;
      width: 48px;
      height: 48px;
      border-radius: 50%;
      text-align: center;
      line-height: 48px;
      background: rgb(89, 209, 255);
      font-size: 16px;
      margin-right: 15px;
      // border: 1px solid silver
    }
    .skeleton_content {
      li {
        font-size: 16px;
      }
      li:nth-child(2) {
        font-size: 13px;
        color: silver;
      }
      li:nth-child(5),
      li:nth-child(6) {
        font-size: 13px;
        margin-top: 10px;
        color: rgb(117, 116, 116);
      }
    }
    /deep/ .van-icon {
      // color: silver;
      font-size: 18px;
    }
  }
  .color {
    color: dodgerblue;
  }
  .color1 {
    color: silver;
  }
  .left {
    float: left;
  }
  .right {
    float: right;
  }
  .active {
    display: none;
  }
  .show {
    // background-color: #f8f4f4;
    display: inline-block;
  }
  .active1 {
    // background-color: #f8f4f4;
    display: inlin-block;
  }
}
.clearfix::after {
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  zoom: 1;
}
</style>
